<?php

namespace app\index\controller;

use app\common\model\AppraiseModel;
use think\Controller;
use think\Db;
use think\Request;

vendor('qiniu/php-sdk/autoload.php');

use Qiniu\Auth;
use Qiniu\Storage\UploadManager; //实例化上传类

class Circle extends Controller
{


    public function circleList(){

        //查询圈子分类
        $circle_tag = Db::name('fc_tags')
            ->field('id,data_name')
            ->order('data_sort','desc')
            ->limit(0,8)
            ->select();

        //查询攻略列表
        $param = request()->param();

        $data = [];
        if (array_key_exists('kinds',$param) && $param['kinds']){

            //友圈
            $circleWhere['t1.is_pass'] = 1;
            $circleWhere['t1.is_del']  = 0;
            $circleWhere['t1.is_display']  = 0;
            $circleWhere['t1.fc_id']  = $param['kinds'];

            $data = Db::name('friends_circle')
                ->alias('t1')
                ->field('
                    t1.*,
                    t2.nickname,t2.user_icon
                    ')
                ->join("lv_user t2","t1.uid = t2.uid",'left')
                ->where($circleWhere)
                ->order('f_id','desc')
                ->paginate(7,false,['query' => request()->param()]);

            $mainData = $data->items();

            $list = [];
            foreach ($mainData as $k0 => $v0){

                $list[$k0]['id'] = $v0['f_id'];
                $titleCount = self::utf8_strlen($v0['fc_title']);
                $list[$k0]['title'] = $titleCount>30?mb_substr($v0['fc_title'],0,30).'...':$v0['fc_title'];

                if ($v0['status'] == 1){

                    $image = explode(',',$v0['image']);
                    $list[$k0]['image'] = $image[0];

                    $list[$k0]['content'] = mb_substr($v0['content'],0,45);


                }else{

                    $list[$k0]['image'] = $v0['video']."?vframe/jpg/offset/1";
                    $list[$k0]['content'] = mb_substr($v0['video_content'],0,45);

                }

                $list[$k0]['like_num'] = $v0['like_num']*1 + $v0['set_like_num']*1;
                $list[$k0]['read_num'] = $v0['read_num']*1 + $v0['set_read_num']*1;
                $list[$k0]['share_num'] = $v0['set_share_num']*1 + $v0['share_num']*1;

                $list[$k0]['is_video'] = $v0['status']==2?1:0;
                $list[$k0]['is_method'] = 0;

                $list[$k0]['nickname'] = $v0['nickname'];
                $list[$k0]['user_icon'] = $v0['user_icon'];
                $list[$k0]['time'] = time_ago($v0['create_time']);

            }

        }else{
            //攻略
            $methodWhere['t1.is_pass'] = 1;
            $methodWhere['t1.is_del']  = 0;
            $methodWhere['t1.is_display']  = 0;

            $title = input('param.title');
            if($title){
                $methodWhere['t1.title'] = ['like','%'.$title.'%'];
            }

            $data = Db::name('method')
                ->alias('t1')
                ->field('
                    t1.*,
                    t2.nickname,t2.user_icon
                    ')
                ->join("lv_user t2","t1.uid = t2.uid",'left')
                ->where($methodWhere)
                ->order('is_select','desc')
                ->order('mid','desc')
                ->paginate(7,false,['query' => request()->param()]);

            $mainData = $data->items();

            $list = [];
            foreach ($mainData as $k => $v){

                $list[$k]['id'] = $v['mid'];
                $list[$k]['title'] = $v['title'];

                $titleCount = self::utf8_strlen($v['title']);
                $list[$k]['title'] = $titleCount>30?mb_substr($v['title'],0,30).'...':$v['title'];

                $image = explode(',',$v['image']);
                $list[$k]['image'] = $image[0];

                $content = json_decode($v['content'],true);
                $list[$k]['content'] = json_decode($v['content'],true);

                $content_str = '';
                foreach ($content as $k2 => $v2){
                    $content_str .= $v2['data'];
                }
                $list[$k]['content'] = mb_substr($content_str,0,45);
                $list[$k]['content'] .= '...';

                $list[$k]['like_num'] = $v['like_num']*1 + $v['set_like_num']*1;
                $list[$k]['read_num'] = $v['read_num']*1 + $v['set_read_num']*1;
                $list[$k]['share_num'] = $v['set_share_num']*1 + $v['share_num']*1;

                $list[$k]['is_video'] = 0;
                $list[$k]['is_method'] = 1;
                $list[$k]['nickname'] = $v['nickname'];
                $list[$k]['user_icon'] = $v['user_icon'];
                $list[$k]['time'] = time_ago($v['create_time']);

            }
        }

        //获取精选攻略
        $wellMethodWhere['t1.is_pass'] = 1;
        $wellMethodWhere['t1.is_del']  = 0;
        $wellMethodWhere['t1.is_display']  = 0;
        $wellMethodWhere['is_select'] = 1;
        $wellMethod = Db::name('method')
            ->alias('t1')
            ->field('t1.mid as id,t1.image,t1.title,t1.create_time,t2.nickname')
            ->join("lv_user t2","t1.uid = t2.uid",'left')
            ->where($wellMethodWhere)
            ->order('is_select','desc')
            ->order('mid','desc')
            ->limit(0,3)
            ->select();

        foreach ($wellMethod as $k3 => $v3){

            $image = explode(',',$v3['image']);
            $wellMethod[$k3]['image'] = $image[0];
            $wellMethod[$k3]['time'] = time_ago($v3['create_time']);

            if (mb_strlen($v3['title'])>12){
                $wellMethod[$k3]['title'] = mb_substr($v3['title'],0,12) . '...';
            }

        }

        $this->assign('wellMethod',$wellMethod);
        $this->assign('data',$data);
        $this->assign('list',$list);
        $this->assign('cat',$circle_tag);
        return view();

    }

    public function circle($id){

        /*$circleWhere['t1.is_pass'] = 1;*/
        $circleWhere['t1.is_del']  = 0;
        $circleWhere['t1.is_display']  = 0;
        $circleWhere['t1.f_id']  = $id;

        $data = Db::name('friends_circle')
            ->alias('t1')
            ->field('t1.*,t2.nickname,t2.user_icon,t3.data_name as circle_type')
            ->join("lv_user t2","t1.uid = t2.uid",'left')
            ->join("lv_fc_tags t3","t1.fc_id = t3.id",'left')
            ->where($circleWhere)
            ->find();

        $data["fc_content"] = json_decode($data['fc_content'],true);
        $data['create_time'] = time_ago($data['create_time']);

        //友圈
        //攻略
        $goodWhere['t1.is_pass'] = 1;
        $goodWhere['t1.is_del']  = 0;
        $goodWhere['t1.is_display']  = 0;

        $goodData = Db::name('friends_circle')
            ->alias('t1')
            ->where($goodWhere)
            ->order('like_num','desc')
            ->limit(3)
            ->select();

        foreach ($goodData as $k0 => $v0){

            if ($v0['status'] == 1){

                $image = explode(',',$v0['image']);
                $goodData[$k0]['image'] = $image[0];


            }else{

                $goodData[$k0]['image'] = $v0['video']."?vframe/jpg/offset/1";
                $goodData[$k0]['content'] = '';

            }

            if (mb_strlen($v0['fc_title'])>10){
                $goodData[$k0]['fc_title'] = mb_substr($v0['fc_title'],0,10) . '...';
            }
        }


        if ($data['status'] == 2){
            $data['image_cover'] = $data['video']."?vframe/jpg/offset/1";
        }

        //判断是否数收藏该酒店
        $is_collect = 0;

        if (session('uid')) {
            $find_collect = Db::name('collect')->where('type',6)->where('other_id',$id)->find();

            if (!empty($find_collect)) {
                $is_collect = 1;
            }
        }
        
        $this->assign('is_select',$is_collect);

        $this->assign('goodData',$goodData);
        $this->assign('data',$data);
        if ($data['status'] == 1){
            return view();
        }else{
            return view('video');
        }

    }

    public function method($id){

        /*$circleWhere['t1.is_pass'] = 1;*/
        $circleWhere['t1.is_del']  = 0;
        $circleWhere['t1.is_display']  = 0;
        $circleWhere['t1.mid']  = $id;

        $data = Db::name('method')
                ->alias('t1')
                ->field('t1.*,t2.nickname,t2.user_icon')
                ->join("lv_user t2","t1.uid = t2.uid",'left')
                ->where($circleWhere)
                ->find();

        $data["content"] = json_decode($data['content'],true);
        $data['create_time'] = time_ago($data['create_time']);

        //查询相关景点
        $view_id = explode(',',$data['view_id']);

        $view_where['tour_id']=  ['IN',$view_id];
        $view_where['is_del']=  0;
        $view_where['is_display']=  0;
        $view = Db::name('tours')->field('tour_id,tour_name,tour_covers')->where($view_where)->select();

        //判断是否数收藏
        $is_collect = 0;

        if (session('uid')) {
            $find_collect = Db::name('collect')->where('type',5)->where('other_id',$id)->find();

            if (!empty($find_collect)) {
                $is_collect = 1;
            }
        }
        
        $this->assign('is_select',$is_collect);


        $this->assign('view',$view);
        $this->assign('data',$data);

        return view();

    }

    public function circleComment(){
        if(Request::instance()->isAjax()){
            $post = Request::instance()->post();
            //获取全部评论
            $where['wid'] = $post['id'];
            $where['t1.is_display'] = 0;
            $where['t1.is_del'] = 0;
            $comment = Db::name('comment_circle')
                ->alias('t1')
                ->field("t1.*,t2.nickname,t2.user_icon,t3.nickname as at_nickname")
                ->join("__USER__ t2",'t1.uid=t2.uid','LEFT')
                ->join("__USER__ t3",'t1.puid=t3.uid','LEFT')
                ->where($where)
                ->order("time",'desc')
                ->select();

            $topComment = array();
            $i=0;
            foreach ($comment as $key => $value){
                if ($value['did'] == 0){
                    $topComment[$i]['commentId'] = $value['id'];
                    $topComment[$i]['commentUid'] = $value['uid'];
                    $topComment[$i]['commentName'] = $value['nickname'];
                    $topComment[$i]['commentIcon'] = $value['user_icon'];
                    $topComment[$i]['commentTime'] = $value['time'];
                    $topComment[$i]['commentContent'] = $value['content'];
                    $topComment[$i]['commentLikeNum'] = $value['like_num'];
                    $topComment[$i]['commentHf'] = array();
                    $i++;
                }
            }

            $a = 0;
            foreach ($topComment as $k => $v){
                foreach ($comment as $k1 => $v1){
                    if ($v['commentId'] == $v1['did']){
                        $topComment[$k]['commentHf'][$a]['hfId'] = $v1['id'];
                        $topComment[$k]['commentHf'][$a]['hfUid'] = $v1['uid'];
                        $topComment[$k]['commentHf'][$a]['hfName'] = $v1['nickname'];
                        $topComment[$k]['commentHf'][$a]['hfTime'] = $v1['time'];
                        $topComment[$k]['commentHf'][$a]['hfContent'] = $v1['content'];
                        $topComment[$k]['commentHf'][$a]['atName'] = $v1['at_nickname'];
                        $topComment[$k]['commentHf'][$a]['hfLikeNum'] = $v1['like_num'];
                    }
                    $a++;
                }
            }

            return json($topComment);
        }
    }

    public function methodComment(){
        if(Request::instance()->isAjax()){
            $post = Request::instance()->post();
            //获取全部评论
            $where['wid'] = $post['id'];
            $where['t1.is_display'] = 0;
            $where['t1.is_del'] = 0;
            $comment = Db::name('comment_method')
                ->alias('t1')
                ->field("t1.*,t2.nickname,t2.user_icon,t3.nickname as at_nickname")
                ->join("__USER__ t2",'t1.uid=t2.uid','LEFT')
                ->join("__USER__ t3",'t1.puid=t3.uid','LEFT')
                ->where($where)
                ->order("time",'desc')
                ->select();

            $topComment = array();
            $i=0;
            foreach ($comment as $key => $value){
                if ($value['did'] == 0){
                    $topComment[$i]['commentId'] = $value['id'];
                    $topComment[$i]['commentUid'] = $value['uid'];
                    $topComment[$i]['commentName'] = $value['nickname'];
                    $topComment[$i]['commentIcon'] = $value['user_icon'];
                    $topComment[$i]['commentTime'] = $value['time'];
                    $topComment[$i]['commentContent'] = $value['content'];
                    $topComment[$i]['commentLikeNum'] = $value['like_num'];
                    $topComment[$i]['commentHf'] = array();
                    $i++;
                }
            }

            $a = 0;
            foreach ($topComment as $k => $v){
                foreach ($comment as $k1 => $v1){
                    if ($v['commentId'] == $v1['did']){
                        $topComment[$k]['commentHf'][$a]['hfId'] = $v1['id'];
                        $topComment[$k]['commentHf'][$a]['hfUid'] = $v1['uid'];
                        $topComment[$k]['commentHf'][$a]['hfName'] = $v1['nickname'];
                        $topComment[$k]['commentHf'][$a]['hfTime'] = $v1['time'];
                        $topComment[$k]['commentHf'][$a]['hfContent'] = $v1['content'];
                        $topComment[$k]['commentHf'][$a]['atName'] = $v1['at_nickname'];
                        $topComment[$k]['commentHf'][$a]['hfLikeNum'] = $v1['like_num'];
                    }
                    $a++;
                }
            }

            return json($topComment);
        }
    }

    public function addComment(){
        if(Request::instance()->isPost()){

            $post = Request::instance()->post();

            $post['uid'] = session('uid');

            //敏感词的处理
            $mingan = Db::name('mingan')->where('is_del',0)->select();
            $arr = [];
            foreach ($mingan as $k=>$v){
                array_push($arr,$v['content']);
            }
            $badword1 = array_combine($arr,array_fill(0,count($arr),'***'));
            $post['content'] = strtr($post['content'], $badword1);
            $saveData = array(
                'wid'=>$post['id'],//文章id
                'uid'=>$post['uid'],
                'content'=>$post['content'],
                'time'=>date("Y-m-d H:i:s")
            );
            if($post['type']==1){
                $res = Db::name('comment_method')->insertGetId($saveData);
            }else{
                $res = Db::name('comment_circle')->insertGetId($saveData);
            }
            if($res){
                if($post['type']==1){
                    //获取攻略的
                    $artcileInfo = Db::name('method')->field('uid')->where('mid',$post['id'])->find();
                }else{
                    $artcileInfo = Db::name('friends_circle')->field('uid')->where('f_id',$post['id'])->find();
                }
                //敏感词的处理
                $mingan = Db::name('mingan')->where('is_del',0)->select();
                $arr = [];
                foreach ($mingan as $k=>$v){
                    array_push($arr,$v['content']);
                }
                $badword1 = array_combine($arr,array_fill(0,count($arr),'***'));
                $post['content'] = strtr($post['content'], $badword1);
                //插入消息
                if($post['type']==1){
                    $messageData = [
                        'type'=> 1,
                        'wid' => $post['id'],
                        'time' =>date("Y-m-d H:i:s"),
                        'kinds'=>1,
                        'comment_content' => $post['content'],
                        'comment_uid' => $post['uid'],
                        'uid'=>$artcileInfo['uid']
                    ];
                    Db::name('comment_method_message')->insert($messageData);
                }else{
                    $messageData = [
                        'type'=> 1,
                        'wid' => $post['id'],
                        'time' =>date("Y-m-d H:i:s"),
                        'kinds'=>2,
                        'comment_content' => $post['content'],
                        'comment_uid' => $post['uid'],
                        'uid'=>$artcileInfo['uid']
                    ];
                    Db::name('comment_message')->insert($messageData);
                }

                return json(array('code'=>'200','msg'=>'评论成功','id'=>$res));
            }else{
                return json(array('code'=>'400','msg'=>'评论失败'));
            }
        }
    }

    //评论回复接口
    public function addCircleReplay()
    {
        if(Request::instance()->isPost()){
            $post = Request::instance()->post();

            $post['uid'] = session('uid');
            //获取回复的评论id
            if($post['type']==1){
                $theCommentFind = Db::name('comment_method')->where("id",$post['pid'])->find();
            }else{
                $theCommentFind = Db::name('comment_circle')->where("id",$post['pid'])->find();
            }
            //敏感词的处理
            $mingan = Db::name('mingan')->where('is_del',0)->select();
            $arr = [];
            foreach ($mingan as $k=>$v){
                array_push($arr,$v['content']);
            }
            $badword1 = array_combine($arr,array_fill(0,count($arr),'***'));
            $post['content'] = strtr($post['content'], $badword1);
            $saveData = array(
                'wid'=>$theCommentFind['wid'],//文章id
                'uid'=>$post['uid'],//用户id
                'content'=>$post['content'],
                'time'=>date("Y-m-d H:i:s"),
                'did'=>$theCommentFind['did']?$theCommentFind['did']:$post['pid'],//楼主id
                'pid'=>$post['pid'], //父级id
                'puid'=>$theCommentFind['uid'] //父级id
            );
            if($post['type']==1){
                $res = Db::name('comment_method')->insertGetId($saveData);
            }else{
                $res = Db::name('comment_circle')->insertGetId($saveData);
            }
            if($res){
                if($post['type']==1){
                    //插入消息
                    $messageData = [
                        'type'=> 2,
                        'wid' => $theCommentFind['wid'],
                        'kinds'=>1,
                        'time' =>date("Y-m-d H:i:s"),
                        'comment_content' => $post['content'],
                        'comment_uid' => $post['uid'],
                        'self_comment' => $theCommentFind['content'],
                        'uid'=>$theCommentFind['uid']
                    ];
                    Db::name('comment_method_message')->insert($messageData);
                }else{
                    //插入消息
                    $messageData = [
                        'type'=> 2,
                        'wid' => $theCommentFind['wid'],
                        'kinds'=>2,
                        'time' =>date("Y-m-d H:i:s"),
                        'comment_content' => $post['content'],
                        'comment_uid' => $post['uid'],
                        'self_comment' => $theCommentFind['content'],
                        'uid'=>$theCommentFind['uid']
                    ];
                    Db::name('comment_message')->insert($messageData);
                }

                return json(array('code'=>'200','msg'=>'回复成功','id'=>$res));
            }else{
                return json(array('code'=>'400','msg'=>'回复失败'));
            }
        }
    }

    //写攻略
    public function writeMethod(){

        //查询所有景点
        $where['is_del'] = 0;
        $where['is_display'] = 0;

        $tour = Db::name('tours')->field('tour_id,tour_name')->where($where)->select();

        $this->assign('tour',$tour);
        return view();

    }

    public function uploadCircleImg()
    {
        $file = request()->file('file');
        // 要上传图片的本地路径
        $filePath = $file->getRealPath();
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        $key = 'Method/test/' . substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;

        // 需要填写你的 Access Key 和 Secret Key
        // 构建鉴权对象
        $accessKey = config("qiniu")["accessKey"];
        $secretKey = config("qiniu")["secretKey"];

        $auth = new Auth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = config("qiniu")["bucket"];
        //域名
        $domain = config("qiniu")["domain"];
        $token = $auth->uploadToken($bucket);

        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return ["code" => 0, "msg" => $err, "data" => ""];
        } else {
            //返回图片的完整URL
            $imgPath = $domain . '/' . $key;

            return ["code" => 1, "msg" => "上传成功",'path'=>$imgPath];
        }
    }

    public function addMethod(){

        $param = request()->post();

        unset($param['file']);
        unset($param['view_id_check']);
        unset($param['is_read']);

        $content = [];
        $canAdd = 0;
        $image_arr = [];
        $mtext = '';
        foreach($param['data'] as $k => $v){

            $content[$k]['data'] = $v;
            $content[$k]['image'] = $param['image'][$k];

            if ($v != '' || $param['image'][$k] != ''){
                $canAdd++;
            }

            if ($param['image'][$k] != ''){
                $image_arr[] = $param['image'][$k];
            }

            if ($v != ''){
                $mtext .= $v;
            }

        }

        if (!$canAdd){
            $this->error('请填写内容');
        }

        $tourWhere['tour_id'] = ['in',explode(',',$param['view_id'])];
        $tour = Db::name('tours')->where($tourWhere)->select();

        $tour_name_arr = [];
        foreach ($tour as $k2 => $v2){
            $tour_name_arr[] = $v2['tour_name'];
        }

        $addData = [
            'view_id'  =>  $param['view_id'],
            'view_name' => implode(',',$tour_name_arr),
            'title' =>  $param['title'],
            'content' =>  json_encode($content),
            'image' =>  implode(',',$image_arr),
            'uid' =>   session('uid'),
            'is_pass' =>  '0',
            'create_time' =>  date('Y-m-d H:i:s'),
            'mtext' =>$mtext
        ];

        $res = Db::name('method')->insertGetId($addData);


        if ($res){
            $this->success('发布成功');
        }else{
            $this->error('发布失败');
        }

    }

    public function writeCircle(){

        $where['is_display'] = 0;
        $fc_tag = Db::name('fc_tags')->field('id,data_name')->order('data_sort','desc')->where($where)->select();

        $this->assign('fc_tag',$fc_tag);
        return view();

    }

    public function addCircle(){

        $param = request()->post();

        unset($param['file']);
        unset($param['is_read']);

        $content = [];
        $canAdd = 0;
        $image_arr = [];
        $mtext = '';
        foreach($param['data'] as $k => $v){

            $content[$k]['data'] = $v;
            $content[$k]['image'] = $param['image'][$k];

            if ($v != '' || $param['image'][$k] != ''){
                $canAdd++;
            }

            if ($param['image'][$k] != ''){
                $image_arr[] = $param['image'][$k];
            }

            if ($v != ''){
                $mtext .= $v;
            }

        }

        if (!$canAdd){
            $this->error('请填写内容');
        }

        $addData = [
            'fc_title'    =>  $param['title'],
            'fc_id'       =>  $param['fc_id'],
            'fc_content'  =>  json_encode($content),
            'image'       =>  implode(',',$image_arr),
            'uid'         =>  session('uid'),
            'status'      =>  1,
            'content'     =>  $mtext,
            'create_time' =>  date('Y-m-d H:i:s')
        ];

        $res = Db::name('friends_circle')->insertGetId($addData);

        if ($res){
            $this->success('发布成功');
        }else{
            $this->error('发布失败');
        }

    }

    //发布视频友圈
    public function writeVideoCircle(){

        if (request()->isPost()){

            $param = request()->post();

            unset($param['file']);
            unset($param['is_read']);

            $videoPath = config("qiniu")['domain'] . '/' . $param['video_path'];

            $addData = [
                'fc_title'       =>  $param['title'],
                'fc_id'          =>  $param['fc_id'],
                'video'          =>  $videoPath,
                'video_content'  =>  $param['video_content'],
                'video_covers'   => $videoPath .'/'. '?vframe/jpg/offset/5',
                'uid'            =>  session('uid'),
                'status'         =>  2,
                'create_time'    =>  date('Y-m-d H:i:s')
            ];

            $res = Db::name('friends_circle')->insertGetId($addData);

            if ($res){
                $this->success('发布成功');
            }else{
                $this->error('发布失败');
            }

        }else{
            $where['is_display'] = 0;
            $fc_tag = Db::name('fc_tags')->field('id,data_name')->order('data_sort','desc')->where($where)->select();

            $this->assign('fc_tag',$fc_tag);

            $qiniuConf = config('qiniu');

            $this->assign('domain',$qiniuConf['domain']);
            $this->assign('token',self::uploadToken());
            return view();

        }

    }

    //获取七牛TOKEN
    private function uploadToken(){
        $accessKey = config("qiniu")["accessKey"];
        $secretKey = config("qiniu")["secretKey"];
        // 初始化签权对象

        $auth = new Auth($accessKey, $secretKey);

        $bucket = config("qiniu")["bucket"];

       return $auth->uploadToken($bucket,null,7200);
    }

    private function utf8_strlen($string = null) {
        preg_match_all('/./us', $string, $match);
        return count($match[0]);
    }

}